﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Security;
using WxSDK.BLL;
using WxSDK.CacheSys;
using WxSDK.Model;
namespace WxSDK
{
    /// <summary>
    /// 微信开发类   微信事件接收页面继承此类即可 appid 为用户id  存储了用户的授权信息
    /// 继承此类的页面必须删除Html构造 . 否则可能会验证失败
    /// </summary>
    public class WeChatDev : WeChatEvent
    {
        WeChatMsg WeChatMsg = new WeChatMsg();
        WxSDK.Model.wx_member Member;
        WxCarroit.WxSdkEvan Evan = new WxCarroit.WxSdkEvan();
        public int MemberId = 0;
        public WeChatDev()
        {
            this.Load += new EventHandler(WeChatDevPage_Load);
        }


        void WeChatDevPage_Load(object sender, EventArgs e)
        {
            int.TryParse(WeChatCommon.get_p("mid"), out MemberId);

            if (MemberId < 1) //如果没有ID
            {

                Response.Write("配置用户ID 不能为空");
            }
            else if (!new BLL.Wx_Member().Exists(MemberId))
            {
                Response.Write("配置用户ID 不存在");
            }
            else
            {
                Member = WeChatMemory.MemberInfo(MemberId);
                if (string.IsNullOrEmpty(WeChatCommon.get_p("echostr"))) //这是消息事件
                {
                    StreamReader reader = new StreamReader(Request.InputStream);
                    string xml = reader.ReadToEnd();
                    WeChatMsg.XmlStr = xml;
                    string MsgType = WeChatMsg.GetXmlInfo("MsgType");
                    switch (MsgType)
                    {
                        case "event"://如果是事件
                            Wx_Events(xml, WeChatMsg.GetXmlInfo("Event"));
                            break;
                        case "text"://如果是文本消息
                            m_text(MemberId, WeChatCommon.XmlToModel<WeChatModel.Msg_Txt>(xml, new WeChatModel.Msg_Txt()));
                            WeChatReciveMsgHandle.ReciveTxtMsgHandle(WeChatMsg, MemberId);
                            //WeChatMsg.MarkTxtMsg(WeChatMsg.GetXmlInfo("Content") + "，您的OpenID=" + WeChatMsg.GetXmlInfo("FromUserName"));
                            break;
                        case "image": //图片消息
                            m_image(MemberId, WeChatCommon.XmlToModel<WeChatModel.Msg_Pic>(xml, new WeChatModel.Msg_Pic()));
                            WeChatReciveMsgHandle.ReciveImageMsgHandle(WeChatMsg, MemberId);
                            break;
                        case "voice"://语音消息
                            m_voice(MemberId, WeChatCommon.XmlToModel<WeChatModel.Msg_Voice>(xml, new WeChatModel.Msg_Voice()));
                            WeChatReciveMsgHandle.ReciveVoiceMsgHandle(WeChatMsg, MemberId);
                            break;
                        case "video"://视频消息
                            m_video(MemberId, WeChatCommon.XmlToModel<WeChatModel.Msg_Video>(xml, new WeChatModel.Msg_Video()));
                            WeChatReciveMsgHandle.ReciveVideoMsgHandle(WeChatMsg, MemberId);
                            break;
                        case "shortvideo": //小视屏消息
                            m_shortvideo(MemberId, WeChatCommon.XmlToModel<WeChatModel.Msg_ShortVideo>(xml, new WeChatModel.Msg_ShortVideo()));
                            WeChatReciveMsgHandle.ReciveShortVideoMsgHandle(WeChatMsg, MemberId);
                            break;
                        case "location"://地理位置
                            m_location(MemberId, WeChatCommon.XmlToModel<WeChatModel.Msg_Location>(xml, new WeChatModel.Msg_Location()));
                            WeChatReciveMsgHandle.ReciveLocationMsgHandle(WeChatMsg, MemberId);
                            break;
                        case "link":// 链接消息
                            m_link(MemberId, WeChatCommon.XmlToModel<WeChatModel.Msg_Link>(xml, new WeChatModel.Msg_Link()));
                            WeChatReciveMsgHandle.ReciveLinkMsgHandle(WeChatMsg, MemberId);
                            break;
                        default:
                            WeChatReciveMsgHandle.ReciveOtherMsgHandle(WeChatMsg, MemberId);
                            break;
                    }
                }
                else
                {
                    //这是验证事件  以下是服务器配置，让微信转发信息至当前服务器
                    WxSerConfig();
                }
            }
        }

        /// <summary>
        /// 微信服务器验证
        /// </summary>
        public void WxSerConfig()
        {
            string echostr = WeChatCommon.get_p("echostr");
            string signature = WeChatCommon.get_p("signature");
            string timestamp = WeChatCommon.get_p("timestamp");
            string nonce = WeChatCommon.get_p("nonce");
            string token = Member.TOKEN; //"34ifjwer908gje59g8h3j4t048ug";
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);     //字典排序
            string tmpStr = string.Join("", ArrTmp);
            tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
            tmpStr = tmpStr.ToLower();
            if (tmpStr == signature.ToLower())
            {
                Response.Write(echostr);
            }
        }


        /// <summary>
        /// 处理微信事件
        /// </summary>
        /// <param name="etype"></param>
        public void Wx_Events(string xml,string etype)
        {

            switch (etype)
            {
                case "subscribe": //订阅事件
                    if (string.IsNullOrEmpty(WeChatMsg.GetXmlInfo("EventKey"))) //没有参数  正常 关注
                    {
                        e_subscribe(MemberId, WeChatCommon.XmlToModel<WeChatModel.Event_Subscribe>(xml, new WeChatModel.Event_Subscribe()));
                        //WeChatMsg.MarkTxtMsg("欢迎您订阅【正常订阅】，您的OpenID=" + WeChatMsg.GetXmlInfo("FromUserName"));
                        WeChatReciveMsgHandle.ReciveSubscribeMsgHandle(WeChatMsg, MemberId);
                    }
                    else //有参数  扫描待参数的二维码
                    {  
                        e_subscribe_para(MemberId, WeChatCommon.XmlToModel<WeChatModel.Event_SubscribePara>(xml, new WeChatModel.Event_SubscribePara()));
                        WeChatReciveMsgHandle.ReciveSubscribeMsgHandle(WeChatMsg, MemberId);
                        //WeChatMsg.MarkTxtMsg("欢迎您订阅【扫描带参数的二维码】，您的OpenID=" + WeChatMsg.GetXmlInfo("FromUserName") + "，您扫描二维码的参数：" + WeChatMsg.GetXmlInfo("EventKey"));
                    }
                    break;
                case "unsubscribe": //取消订阅事件
                    e_unsubscribe(MemberId, WeChatCommon.XmlToModel<WeChatModel.Event_UnSubscribe>(xml, new WeChatModel.Event_UnSubscribe()));
                    //WeChatCommon.Log("un订阅", WeChatMsg.GetXmlInfo("FromUserName"));
                    break;
                case "SCAN": //用户已经关注后扫描待参数的二维码事件
                    e_scan(MemberId, WeChatCommon.XmlToModel<WeChatModel.Event_Scan>(xml, new WeChatModel.Event_Scan()));
                    WeChatMsg.MarkTxtMsg("欢迎您扫描二维码【已经关注后扫描带参数的二维码】，您的OpenID=" + WeChatMsg.GetXmlInfo("FromUserName") + "，您扫描二维码的参数：" + WeChatMsg.GetXmlInfo("EventKey"));
                    break;
                case "LOCATION": //上报地理位置事件
                    e_location(MemberId, WeChatCommon.XmlToModel<WeChatModel.Event_Location>(xml, new WeChatModel.Event_Location()));
                    WeChatModel.Event_Location l = WeChatCommon.XmlToModel<WeChatModel.Event_Location>(xml, new WeChatModel.Event_Location());
                    WeChatMsg.MarkTxtMsg("经纬度 : " + l.Longitude + " , " + l.Latitude + " 精度 : " + l.Precision + " 具体位置 : " + WxSDK.WeChatLocation.GetLocation(l.Latitude, l.Longitude).result.formatted_address);
                    break;
                case "CLICK": //自定义菜单事件 点击菜单拉取消息时的事件推送
                    e_click(MemberId, WeChatCommon.XmlToModel<WeChatModel.Event_Click>(xml, new WeChatModel.Event_Click()));
                    //SendTuWen();
                    //WeChatMsg.MarkTxtMsg("点击菜单事件CLICK，您的OpenID=" + WeChatMsg.GetXmlInfo("FromUserName") + "，EventKey=" + WeChatMsg.GetXmlInfo("EventKey"));
                    break;
                case "VIEW": //自定义菜单事件 点击菜单跳转链接时的事件推送  此事件不会推送了
                    e_view(MemberId, WeChatCommon.XmlToModel<WeChatModel.Event_View>(xml, new WeChatModel.Event_View()));
                    break;
                case "TEMPLATESENDJOBFINISH": //模板消息发送完成后的结果推送
                    e_templatesendjobfinish(MemberId, WeChatCommon.XmlToModel<WeChatModel.Event_TemplateSendJobFinish>(xml, new WeChatModel.Event_TemplateSendJobFinish()));
                    break;
                default:
                    break;
            }
        }

    }
}
